package com.woniuxy.background.controller;

import com.woniuxy.background.advice.SysLog;
import com.woniuxy.background.common.RestResult;
import com.woniuxy.background.pojo.Admin;
import com.woniuxy.background.pojo.Role;
import com.woniuxy.background.pojo.User;
import com.woniuxy.background.service.AdminService;
import com.woniuxy.background.service.RolesService;
import com.woniuxy.background.service.UsersService;
import com.woniuxy.background.vo.AdminPwdVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private RolesService rolesService;

    @Autowired
    private UsersService usersService;

    @Autowired
    private AdminService adminService;

    /**
     * 管理员登录
     * @param admin
     * @return
     */
    @PostMapping("/subLogin")
    @ResponseBody
    public RestResult subLogin(Admin admin){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(),admin.getPassword());

        //认证
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return RestResult.failed("认证失败");
        }
        return RestResult.success();

    }


    @DeleteMapping("/delete/{adminId}")
    @ResponseBody
    @SysLog(value = "删除管理员")
    @RequiresPermissions("sys:admin:delete")
    public RestResult deleteUser(@PathVariable("adminId") int adminId){
        try {
            adminService.deleteByPrimaryKey(adminId);
        }catch (Exception e){
            e.printStackTrace();
            return RestResult.failed("删除失败！");
        }
        return RestResult.success("删除成功！");
    }

    @RequestMapping("/list")
    @ResponseBody
    @RequiresPermissions("sys:admin:list")
    public RestResult adminList(){
        List<Admin> admins = adminService.adminList();
        List<Admin> list = new ArrayList<Admin>();
        for (Admin a : admins){
            a.setRole(rolesService.selectByPrimaryKey(a.getRoleId()));
            list.add(a);
        }
        return RestResult.success(list);
    }

    @PostMapping("/updAdmin")
    @ResponseBody
    @SysLog(value = "更新管理员")
    @RequiresPermissions("sys:admin:update")
    public RestResult updUser(Admin admin){
        try {
            adminService.updateByPrimaryKeySelective(admin);
        }catch (Exception e){
            e.printStackTrace();
            RestResult.failed("修改失败！");
        }
        return RestResult.success("修改成功！");
    }

    @RequestMapping("/adminEdit/{adminId}")
    @ResponseBody
    public ModelAndView adminEdit(@PathVariable("adminId")int adminId, ModelAndView modelAndView){
        Admin admin = adminService.selectByPrimaryKey(adminId);
        List<Role> roles = rolesService.selectRoles();
        modelAndView.addObject("admin",admin);
        modelAndView.addObject("roles",roles);
        modelAndView.setViewName("sys/editAdmin");
        return modelAndView;
    }

    @RequestMapping("/toAdmin")
    @ResponseBody
    @SysLog(value = "添加为管理员")
    @RequiresPermissions("sys:admin:save")
    public RestResult toAdmin(User user){
       User userAdmin = usersService.findById(user.getUserId());
       Admin admin = new Admin();
       admin.setUsername(userAdmin.getUsername());
       admin.setPassword(userAdmin.getPassword());
       admin.setSalt(userAdmin.getSalt());
       admin.setNickname(userAdmin.getNickName());
       admin.setRoleId(2);

        try {
            adminService.insert(admin);
        }catch (Exception e){
            e.printStackTrace();
            return RestResult.failed("操作失败！");
        }
        return RestResult.success("操作成功！");
    }

    @RequestMapping("/toUpdPwd")
    public ModelAndView userEdit(ModelAndView modelAndView){
        Admin admin = new Admin();
        admin.setUsername(SecurityUtils.getSubject().getPrincipal().toString());
        admin = adminService.selectAdminByName(admin);
        System.out.println("123321312312312"+admin);
        modelAndView.addObject("admin",admin);
        modelAndView.setViewName("sys/updatePwd");
        return modelAndView;
    }

    @PostMapping("/updPwd")
    @ResponseBody
    @SysLog(value = "修改管理员密码")
    @RequiresPermissions("sys:admin:update")
    public RestResult updPwd(AdminPwdVO adminPwdVO){
        System.out.println(adminPwdVO);
        try {
            Admin admin = adminService.selectByPrimaryKey(adminPwdVO.getAdminId());
            if (admin.getPassword().equals(adminPwdVO.getPassword())){
                Admin admin1 = new Admin();
                admin1.setAdminId(adminPwdVO.getAdminId());
                admin1.setPassword(adminPwdVO.getNewPwd());
                System.out.println(adminService.updateByPrimaryKeySelective(admin1));
            }else {
                throw new Exception("原密码错误!");
            }
        }catch (Exception e){
            e.printStackTrace();
            RestResult.failed(e.getMessage());
        }
        return RestResult.success("修改成功！");
    }

}
